<script setup>
import { ref } from 'vue'
import channelSelect from './channelSelect.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { artAddListService } from '@/api/article'
import { artEditListService } from '@/api/article'
import { baseURL } from '@/util/request'
import axios from 'axios'
import { artUpdateListService } from '@/api/article'

const drawerShow = ref(false)
// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}
// 进入抽屉
const open = async (row) => {
  drawerShow.value = true
  if (row.id) {
    console.log('编辑文章')
    const res = await artEditListService(row.id)
    console.log(res)
    formModel.value = res.data.data
    imgUrl.value = baseURL + res.data.data.cover_img
    formModel.value.cover_img = await imageUrlToFile(imgUrl.value, formModel.value.cover_img)
  } else {
    console.log('添加文章')
    formModel.value = { ...defaultModel }
  }
}
const defaultModel = {
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
}
const formModel = ref({
  ...defaultModel
})
const emit = defineEmits(['success'])
// 图片预览逻辑
const imgUrl = ref('')
const fileOnChange = (res) => {
  imgUrl.value = URL.createObjectURL(res.raw)
  formModel.value.cover_img = res.raw
}
defineExpose({ open })

// 发布文章
const editor = ref()
const articlePut = async (str) => {
  formModel.value.state = str
  const data = new FormData()
  for (let key in formModel.value) {
    data.append(key, formModel.value[key]) //不能使用.key的方法，这里的key是"cate_id"这种的!!!
  }
  if (formModel.value.id) {
    console.log('编辑操作')
    const res = await artUpdateListService(data)
    console.log(res)
    emit('success', 'edit')
    drawerShow.value = false
    ElMessage.success('编辑成功!')
  } else {
    const res = await artAddListService(data)
    console.log(res)
    emit('success', 'add')
    ElMessage.success('发布成功!')
    // 重置表单
    formModel.value = { ...defaultModel }
    imgUrl.value = ''
    editor.value.setHTML('')
    drawerShow.value = false
  }
}
</script>
<template>
  <el-drawer
    v-model="drawerShow"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channelSelect v-model="formModel.cate_id" width="100%"></channelSelect>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="fileOnChange"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <QuillEditor
            theme="snow"
            v-model:content="formModel.content"
            ref="editor"
            content-type="html"
          ></QuillEditor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="articlePut('已发布')">发布</el-button>
        <el-button type="info" @click="articlePut('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
